﻿using DFGJ.WMS_PDA.WebAPI.CfgFile;
using DFGK.WMS.Common.Result;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.PTG;
using SqlSugar;
using System.Security.Claims;
using static NPOI.HSSF.Util.HSSFColor;
using DFGK_WMS.Context;

namespace DFGJ.WMS_PDA.WebAPI.Controllers.PDA
{
    /// <summary>
    /// PDA移库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PDATransferBinController : ControllerBase
    {
        private readonly ITransferBinOrderRepository _transferRespository;

        public ITCellRepository _TCellRepository { get; set; }
        public ISqlSugarClient _Client { get; }

        private readonly ILogger<PDATransferBinController> _Logger;

        private readonly DFGK_DB _dbContext;


        public PDATransferBinController(
            ISqlSugarClient client, ITransferBinOrderRepository transferRespository,
            ITCellRepository tCellRepository,
            ILogger<PDATransferBinController> logger,
            DFGK_DB dbContext)
        {
            _Client = client;
            _transferRespository = transferRespository;
            _TCellRepository = tCellRepository;
            _Logger = logger;
            _dbContext = dbContext;
        }


        /// <summary>
        /// 通过移库单编号，找到移库明细信息
        /// </summary>
        /// <param name="oredr"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GettransferBinOrder(string oredr)
        {
            var model = _Client.Queryable<TTransferBinOrderDetail>().First(t => t.OrderSn == oredr);
            return Ok(model);
        }
        /// <summary>
        /// 查询移库单全部单号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetMovementOrder")]
        public IActionResult GetMovementOrder()
        {
            var list = _Client.Queryable<TTransferBinOrder>().ToList();
            return Ok(list);
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SubmitTransferCell(int id)
        {
            string msg = string.Empty;
            if (id != 0)
            {
                var targetCells = _transferRespository.SubmitTransferCell(id, out msg);
            }

            return Ok(msg);
        }
        /// <summary>
        /// 执行移库
        /// </summary>
        /// <returns>已弃用</returns>
        [HttpPost]
        public IActionResult GetExecInstructFinished(int id)
        {
            string msg = string.Empty;
            var IsOk= _transferRespository.ExecInstructFinished(id,out msg);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！" + msg, "500"));
        }
        /// <summary>
        /// 通过仓位查询物料信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTInventoryById(string CangCode)
        {
            var targetCells = _Client.Queryable<TInventory>().Where(c => c.LocationCode == CangCode).ToList();
            if (targetCells.Count == 0)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }

            return Ok(BaseResult.Result(targetCells, "查询成功", "200"));


        }

        /// <summary>
        /// 查询所有移库单
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllTransferBin(string? OrderSn)
        {
            int count = 0;
            var targetCells = _transferRespository.GetAllTransferBin(OrderSn,out count);
            if (targetCells!=null)
            {
                return Ok(BaseResult.Result(targetCells, "查询成功", "200",0));
            }

            return Ok(BaseResult.Result(null, "查询失败", "500",count));


        }


        /// <summary>
        /// 判断传入参数有没有这个移库单
        /// </summary>
        /// <returns>已弃用</returns>
        [HttpGet]
        public IActionResult GetTOrderDetail(string? yaction, int wuliao, string? newaction, string? tuopan)
        {


            var model = _Client.Queryable<TTransferBinOrderDetail>().First(t => t.FromLocationCode == yaction && t.MaterialId == wuliao && t.ToLocationCode == newaction);

            if (model != null)
            {
                SubmitTransferCell(model.Id);
            }
            else if (model == null)
            {
                bool result = false;
                TTransferBinOrder transferBin = new TTransferBinOrder();
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                transferBin.CreateUserId = uid;
                transferBin.CreateUserName = uname;
                transferBin.CreateDate = DateTime.Now;
                transferBin.Status = 3;
                var id = _Client.Insertable(transferBin).ExecuteReturnIdentity();
                TTransferBinOrderDetail item = new TTransferBinOrderDetail();
                var a = _Client.Queryable<TMaterial>().First(t => t.Id == wuliao);
                item.OrderId = id;
                item.OrderSn = transferBin.OrderSn;
                item.CreateUserId = transferBin.CreateUserId;
                item.CreateUserName = transferBin.CreateUserName;
                item.CreateDate = transferBin.CreateDate;
                item.ModifyUserId = transferBin.ModifyUserId;
                item.ModifyUserName = transferBin.ModifyUserName;
                item.ModifyDate = transferBin.ModifyDate;
                item.MaterialId = wuliao;
                item.MaterialName = a.Name;
                item.FromLocationCode = yaction;
                item.ToLocationCode = newaction;
                item.Status = 3;
                _Client.Insertable(item).ExecuteCommand();
                SubmitTransferCell(id);

            }
            return Ok(true);
        }

        /// <summary>
        /// 创建移库单验证移库
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CreateTransfer(TTransferBinOrderCreateDTO req)
        {
            string msg = string.Empty;
            string uname = HttpContext.User.FindFirstValue("UserName");
            string runame = HttpContext.User.FindFirstValue("RealName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            var IsOk = _transferRespository.CreateTransfer(req, uid, uname, out msg);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！" + msg, "500"));

        }
    }

    public class MoveItemModel
    {
        ///// <summary>
        ///// 1、浅位入深位；2、深位入深位；3、浅位入浅位；4、深位入浅位
        ///// </summary>
        //public int Type
        //{
        //    get; set;
        //}
        public TCell FromCell
        {
            get; set;
        }

        public TInventory FromInv
        {
            get; set;
        }

        public TCell ToCell
        {
            get; set;
        }

        public TMaterial Material
        {
            get; set;
        }

        public TReceivingOrderDetail OrderDetail
        {
            get; set;
        }
    }
}
